package tools;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author MorWin
 */
public class TestUtil<AnyType extends Comparable<? super AnyType>> {
    public boolean isTestPass(String inputFilePath, String expectedResultFilePath, String className, String methodName)
            throws IOException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //加载用例输入
        BufferedReader inputBufferedReader = loadUseCaseInput(inputFilePath);
        AnyType input;

        //加载用例预期输出
        BufferedReader expectedResultBufferedReader = loadUseCaseInput(expectedResultFilePath);
        AnyType expectedResult;
        String input_line="";
        while((input_line=inputBufferedReader.readLine())!=null) {
            input=(AnyType)input_line;
            expectedResult=(AnyType) expectedResultBufferedReader.readLine();

            //执行测试函数
            Class testedClass = Class.forName(className);
            Method m = testedClass.getMethod(methodName,Object.class);
            AnyType output = (AnyType) m.invoke(testedClass.newInstance(),input);
            //将执行结果与预期结果进行比较
            boolean isEqual = Compare(output, expectedResult);
            if (!isEqual) {
                return false;
            }
        }
        return true;
    }


    public static BufferedReader loadUseCaseInput(String inputPath) throws FileNotFoundException {
        FileReader inputFileReader=new FileReader(inputPath);
        BufferedReader inputBufferedReader=new BufferedReader(inputFileReader);
        return inputBufferedReader;
    }


    public static BufferedReader loadUseCaseOutput(String outputPath) throws FileNotFoundException {
        FileReader outputFileReader=new FileReader(outputPath);
        BufferedReader outputBufferedReader=new BufferedReader(outputFileReader);
        return outputBufferedReader;
    }
    public boolean Compare(AnyType output,AnyType expectedResult){
            return output.toString().equals(expectedResult.toString());
    }
}
